#! /bin/bash
# ******************************************************************************
# * Licensed Materials - Property of IBM
# * IBM Cloud Container Service, 5737-D43
# * (C) Copyright IBM Corp. 2018 All Rights Reserved.
# * US Government Users Restricted Rights - Use, duplication or
# * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
# ******************************************************************************

if [[ $# -ne 4 ]]; then
    echo "Usage: $0 <auth-type> <service-key> <secret-name> <namespace>"
    echo "   Where:-"
    echo "   - <auth-type>   : iam or hmac"
    echo "   - <service-key> : service key, to get the list of keys execute"
    echo "                     ibmcloud resource service-keys --instance-name <instance name>"
    echo "   - <secret-name> : secret name to be assigned"
    echo "   - <namespace>   : K8S namespace under which the secret to be created"
    exit 1
fi

auth_type="$1"
svc_key="$2"
sec_name="$3"
name_space="$4"

if [[ "$auth_type" != "iam" && "$auth_type" != "IAM" &&  "$auth_type" != "hmac" && "$auth_type" != "HMAC" ]]; then
    echo "Error: invalid auth-type, should be \"iam\" or \"hmac\""
    exit 1
fi

os_name=$(uname)


if [[ "$auth_type" == "iam" || "$auth_type" == "IAM" ]]; then
    keys=$(ibmcloud resource service-key $svc_key | grep -e 'apikey:' -e 'resource_instance_id:'); rc=$?
    if [[ $rc -ne 0 ]]; then
       echo "Error: invalid service-key \"$svc_key\""
       exit 1
    fi
    if [[ "$os_name" == "Linux" ]]; then
       API_KEY=$(echo "$keys" | grep -e 'apikey:'| awk '{print $2}' | xargs echo -n | base64 --wrap=0)
       SVC_ID=$(echo "$keys" | grep -e 'resource_instance_id:'| awk '{print $2}' | xargs echo -n | base64 --wrap=0)
    else
       API_KEY=$(echo "$keys" | grep -e 'apikey:'| awk '{print $2}' | xargs echo -n | base64)
       SVC_ID=$(echo "$keys" | grep -e 'resource_instance_id:' | awk '{print $2}' | xargs echo -n | base64)
    fi
else
    keys=$(ibmcloud resource service-key $svc_key | grep -e 'access_key_id:' -e 'secret_access_key:'); rc=$?
    if [[ $rc -ne 0 ]]; then
       echo "Error: invalid service-key \"$svc_key\" or HMAC key not created"
       exit 1
    fi
    ACS_KEY=$(echo "$keys" | grep -e 'access_key_id:' | awk '{print $2}' | xargs echo -n | base64)
    SEC_KEY=$(echo "$keys" | grep -e 'secret_access_key:' | awk '{print $2}' | xargs echo -n | base64)

fi

echo "Creating secret \"$sec_name\"..."

if [[ "$auth_type" == "iam" || "$auth_type" == "IAM" ]]; then

kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
type: ibm/ibmc-s3fs
metadata:
  name: $sec_name 
  namespace: $name_space
data:
  api-key: $API_KEY
  service-instance-id: $SVC_ID
EOF

else #HMAC

kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
type: ibm/ibmc-s3fs
metadata:
  name: $sec_name 
  namespace: $name_space
data:
  access-key: $ACS_KEY
  secret-key: $SEC_KEY
EOF

fi
